Reading Quantity Samples PRO
The Scripting app allows you to query quantity-based health data, such as step count, heart rate, body mass, calories burned, distance, and more, using the global Health.queryQuantitySamples() API.
This guide explains how to retrieve quantity samples and work with the results.
What Are Quantity Samples?
A quantity sample represents a numeric health measurement taken at a specific time or over a time interval. Common examples include:
stepCountheartRatebodyMassactiveEnergyBurneddistanceWalkingRunning
These samples can be either discrete (a single measurement) or cumulative (a value summed over time).
API Overview
Parameters
quantityType: The health data type to query (e.g.,"stepCount","heartRate")startDate/endDate: Time range for filtering sampleslimit: Maximum number of resultsstrictStartDate/strictEndDate: Iftrue, only samples starting/ending exactly at those dates will be includedsortDescriptors: Optional array to sort results bystartDate,endDate, orcount
Sample Code: Reading Step Count
Sample Code: Reading Heart Rate with Unit
Interpreting Sample Types
Each sample returned may be:
HealthQuantitySample: The base classHealthCumulativeQuantitySample: Includes.sumQuantity(unit)HealthDiscreteQuantitySample: Includes.averageQuantity(unit),.maximumQuantity(unit), etc.
You can use instanceof or feature detection to check for extended properties.
Example:
Notes
- The unit passed to
.quantityValue()must match the type (e.g., usecount()for steps,gram(HealthMetricPrefix.kilo)for body mass). - Some types (like heart rate) require compound units like
count().divided(minute()). - The time interval is defined by
startDateandendDateon each sample. - Samples may have an optional
.metadataand.count.
Common Units by Type
Error Handling
Summary
To read quantity samples:
- Call
Health.queryQuantitySamples(type, options) - Loop through the results
- Use
.quantityValue(unit)or.sumQuantity(unit)depending on the type
This API gives you powerful access to time-series health data stored in HealthKit.
